#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib> //stdlib.h
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

void Writer(int wfd)
{
    int number = 0;
    string s = "hello ,I am child";
    char buffer[1024];
    pid_t self = getpid();
    while(true){
        buffer[0] = 0;
        snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),self,number++);
        write(wfd,buffer,strlen(buffer));
        sleep(1);
    }
}

void Reader(int rfd)
{
    char buffer[1024];
    while(true)
    {   buffer[0] = 0;
        ssize_t n = read(rfd,buffer,sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "father get a message[" << getpid() << "]# " << buffer << endl;
        }
        else if(n == 0)
        {
            printf("father read file done!\n");
            return;
        }
        if(n < 0) return ;
    }
}

int main()
{
    int pipefd[2] = {0};
    int ret = pipe(pipefd);
    pid_t id = fork();
    if(id == 0)
    {
        //child 写
        close(pipefd[0]);
        Writer(pipefd[1]);

        exit(0);
    }
    //father读
    
    close(pipefd[1]);

    Reader(pipefd[0]);
    waitpid(id,nullptr,0);
    return 0;
}